from flask import request
from flask_login import login_required

from conf.flask_ini import FlaskIni
from conf.redis_cnx import RedisCnxPool
from medical_kg.entity_tree import EntityTree
from medical_kg.entity_type import EntityType
from web.const import CONTEXT
from web.validation import valid

redis_conn = RedisCnxPool().get_conn()

app = FlaskIni().get_app()
rbac = FlaskIni().get_rbac()
entity_crud_app = EntityTree()
entity_type_app = EntityType()

prefix = f'{CONTEXT}/entity_tree'


@app.route(f'{prefix}/create_child_node', methods=['POST'])
@rbac.allow(roles=['编辑员'], methods=['POST'])
@login_required
def create_child_node():
    parent_uid = request.json['parent_uid']
    name = request.json['name']
    desc = request.json['desc']

    valid(parent_uid, name, desc)

    return entity_crud_app.create_child_node(parent_uid, name, desc)


@app.route(f'{prefix}/delete_node', methods=['POST'])
@rbac.allow(roles=['管理员'], methods=['POST'])
@login_required
def delete_node():
    uid = request.json['uid']

    valid(uid)

    return entity_crud_app.delete_node(uid)


@app.route(f'{prefix}/alter_node_info', methods=['POST'])
@rbac.allow(roles=['编辑员'], methods=['POST'])
@login_required
def alter_node_info():
    uid = request.json['uid']
    name = request.json['name']
    desc = request.json['desc']
    labels = request.json['labels']

    valid(uid, name, desc)

    return entity_crud_app.alter_node_info(uid, name, desc, labels)


@app.route(f'{prefix}/query_node_info', methods=['POST'])
@rbac.allow(roles=['小萌新'], methods=['POST'])
@login_required
def query_node_info():
    uid = request.json['uid']

    valid(uid)

    return entity_crud_app.query_node_info(uid)


@app.route(f'{prefix}/create_entity_type', methods=['POST'])
@rbac.allow(roles=['管理员'], methods=['POST'])
@login_required
def create_entity_type():
    name = request.json['name']
    desc = request.json['desc']

    valid(name, desc)

    return entity_type_app.create_entity_type(name, desc)


@app.route(f'{prefix}/alter_entity_type_name', methods=['POST'])
@rbac.allow(roles=['管理员'], methods=['POST'])
@login_required
def alter_entity_type_name():
    old_name = request.json['old_name']
    new_name = request.json['new_name']
    desc = request.json['desc']

    valid(old_name, new_name, desc)

    return entity_type_app.alter_entity_type_name(old_name, new_name, desc)


@app.route(f'{prefix}/delete_entity_type', methods=['POST'])
@rbac.allow(roles=['管理员'], methods=['POST'])
@login_required
def delete_entity_type():
    name = request.json['name']

    valid(name)

    return entity_type_app.delete_entity_type(name)
